package com.qf.shiro.realm;

import com.qf.shiro.bean.SysBean;
import com.qf.shiro.pojo.SysUser;
import com.qf.shiro.pojo.UserP;
import com.qf.shiro.util.DbUtils;
import com.qf.shiro.util.JdbcUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.DuplicateFormatFlagsException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.err.println("开始认证");
        String username = (String) token.getPrincipal();
        System.err.println("username="+username);

        SysUser user = null;
        try {
            user = getUserInfo(username);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(username, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        System.err.println("用户完成了认证，下一步开始授权");
        return simpleAuthenticationInfo;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.err.println("用户完成了认证，现在开始授权");

        // 授权
        // 获取用户名
        String  account = (String) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 从数据库查询 角色信息
        Set<String> roles = getUserRolesByAccount(account);
        System.err.println("查询到用户的角色"+roles);
        // 从数据库查询权限信息
        Set<String> permissions = getUserPermissionsByAccount(account);
        System.err.println("查询到用户的权限"+permissions);


        simpleAuthorizationInfo.addStringPermissions(permissions);
        simpleAuthorizationInfo.addRoles(roles);


        return simpleAuthorizationInfo;


    }

    /**
     * 查询用户权限
     * @param account
     * @return
     */
    private Set<String> getUserPermissionsByAccount(String account) {

        String sql="SELECT syr.resource_name \n" +
                "FROM sys_user su \n" +
                "LEFT JOIN sys_user_role sur \n" +
                "ON su.user_id=sur.user_id \n" +
                "LEFT JOIN sys_role sr \n" +
                "ON sur.role_id=sr.role_id \n" +
                "LEFT JOIN sys_role_resource srr\n" +
                "ON sr.role_id = srr.role_id\n" +
                "LEFT JOIN sys_resource syr\n" +
                "ON srr.resource_id=syr.resource_id\n" +
                "WHERE su.account=?";
        QueryRunner qr = DbUtils.getQr();
        List<SysBean> beanList=null;
        try {
           beanList = qr.query(sql, new BeanListHandler<SysBean>(SysBean.class), account);
            System.err.println("beamList="+beanList);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
//        ResultSet resultSet = JdbcUtil.executeQuery(sql, account);
        HashSet<String> set = new HashSet<String>();

        for (SysBean sysBean : beanList) {
            set.add(sysBean.getResource_name());
//            System.err.println("permission="+sysBean.getResource_permission());
        }

        System.out.println("set=======>"+set);
        return set;

    }

    /**
     * 查询用户角色
     * @param account
     * @return
     */
    private Set<String> getUserRolesByAccount(String account) {
        String sql="SELECT sr.role_name \n" +
                "FROM sys_user su \n" +
                "LEFT JOIN sys_user_role sur \n" +
                "ON su.user_id=sur.user_id \n" +
                "LEFT JOIN sys_role sr \n" +
                "ON sur.role_id=sr.role_id \n" +
                "WHERE account=?";
        HashSet<String> set = new HashSet<String>();
//        System.err.println("account="+account);
        ResultSet resultSet = JdbcUtil.executeQuery(sql, account);

        try {
            while (resultSet.next()){
                set.add(resultSet.getString("role_name"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return set;
    }


    private SysUser getUserInfo(String username) throws SQLException {
        String sql = "select * from sys_user where account=?";
        QueryRunner qr = DbUtils.getQr();
        SysUser user = qr.query(sql, new BeanHandler<SysUser>(SysUser.class), username);
        System.err.println("user="+user);


        return user;
    }
}
